<?php

namespace Plangame\Model;
use Think\Model;

class UsersModel extends Model {

	/**
	 * [createUser 记录用户微信授权信息]1
	 * @param  [type] $data [授权返回数据]
	 * @return [type]       [操作类型]
	 */
	public function createUser($data) {
		if(empty($data)) { return "";}
		$openId = isset($data['openid']) ? $data['openid'] : '';
		$nickname = isset($data['nickname']) ? $data['nickname'] : '';
		$avatar = isset($data['avatar']) ? $data['avatar'] : '';
		$id = isset($data['id']) ? $data['id'] : '';

		$dataArr = array(
            'openid'=>$openId,
            'nickname'=>$nickname,
            'avatar'=>$avatar,
            'status'=> 2
    	);
			
		if(!empty($openId)) {  
			$map['openid'] = $openId;
		}else {
			$map['id'] = $id;
		}
				
        $users = M('users')->where($map)->find();

        if(empty($users)){  // 插入第一次授权用户
            $dataArr['create_time'] = date("Y-m-d H:i:s");
            $dataArr['types'] = 3;
            $dataArr['weapons'] = json_encode(array(1=>array('skin'=>1,'attack_lv'=>1,'speed_lv'=>1,'blood_lv'=>1,'status'=>1)));
            $ret = M('users')->add($dataArr);
        // 更改则更新用户信息    
        }else {
            if($users['status']!=2) {  // 未授权取值
                if(!empty($users['nickname']) && !empty($users['avatar'])){
                    $dataArr['types'] = 4;  //第二次
                }else{
                    $dataArr['types'] = 3;  //第一次
                }
            }
            $dataArr['update_time'] = date('Y-m-d H:i:s');
            $ret = M('users')->where($map)->save($dataArr);
        }

        if($ret) {
        	$users = M('users')->where($map)->find();
        	//$this->loginLog($users['id']);       	 	
        }
		$users['weapons'] = json_decode($users['weapons'],true);
		return $users;
	}


	/**
     * 用户每日登陆记录
     */
    public function loginLog($uid) {
        $date = date('Y-m-d');
        $map['uid'] = $uid;
        $map['create_time'] = $date;
        $ret = M('users_sign_log')->where($map)->find();
        if(empty($ret)) {
            $data = array('uid'=>$uid,'create_time'=>$date);
            $res = M('users_sign_log')->add($data);
            if(empty($res)) {
            	Log::write('每日登陆记录日志失败','WARN');
            }
            if($res) {
            	$contion['id'] = $uid;
            	$ret2 = M('users')->where($contion)->setInc('sign_num',1);
            	if(empty($ret2)) {
            		Log::write('修改用户每日登陆次数失败','WARN');
            	}

            }
        }
    }	

}


?>